// pages/order/order.js
const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    buyPatterns: true,
    invoice: true,
    addressCol: true,
    total_price: "0",
    buy_type: "1",
    buyType: "1",
    invoiceNeed: "0",
    invoiceType: "2",
    invoiceTextType: "1",
    lastTime: 0,
    captionCol: false,
    orderSubmitCol:false,
		Email:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // if (options.shop_id) {
    //   this.setData({
    //     shop_id: options.shop_id
    //   })
    // }

    if (options.inn_id) {
      this.setData({
        inn_id: options.inn_id
      })
    }

    if (options.formCart) {
      this.setData({
        by_shopping_cart: '1'
      })
    }

    if (options.share_id) {
      this.setData({
        share_id: options.share_id
      })
    }

    if (options.uid) {
      this.setData({
        uid: options.uid
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.data.items = wx.getStorageSync('orderList');
    var that = this;
    //发票授权开关
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.invoiceTitle']) {
          that.setData({
            invoiceAuthorize:'1'
          })
        } else {
          that.setData({
            invoiceAuthorize: '3'
          })
        }
      }
    })

    this.setData({
      orderSubmitCol: false,
      items: wx.getStorageSync('orderList')
    })
    var items = this.data.items;
    var total_price = 0;
    for (var i = 0; i < items.length; i++) {
      total_price = (total_price / 1 + items[i].total / 1).toFixed(2);
    }
    this.addressList();
    this.setData({
      total_price: total_price,
      lastTime: 0
    })
  },
  //地址列表
  addressList: function() {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function(res) {
        if (util.isEmpty(res.data.code)) {
          var addressLength = res.data.data.address_list.length;
          var addressList = res.data.data.address_list;
          for (var i = 0; i < addressList.length; i++) {
            if (addressList[i].is_default == 1) {
              var addressId = addressList[i].aid
            }
          }

          that.setData({
            addressId: addressId,
            address: addressList,
            addressLength: addressLength
          })
        }
      },
      fail: function(fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //添加新地址
  addAddress: function() {
    wx.navigateTo({
      url: '/index/pages/addAddress/addAddress'
    })
  },
  //显示地址弹窗
  selAddress: function() {
    this.setData({
      addressCol: false
    })
  },
  //修改地址
  editorAddress: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/index/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;

    wx.showModal({
      title: '提示',
      content: '确认删除该地址?',
      confirmColor: "#e51927",
      success: function(res) {
        if (res.confirm) {
          api.POST({
            params: {
              aid: id
            },
            url: app.globalData.base_url + 'address/del',
            success: function(res) {
              if (util.isEmpty(res.data.code)) {
                util.showStatus("删除成功")
                that.addressList();
              }
            },
            fail: function(fail) {
              util.showError("网络错误，请检查网络");

            }
          })
        } else if (res.cancel) {
        }
      }
    })
  },

  //选择地址
  radioChange: function(e) {
    var id = e.detail.value
    var that = this;
    var list = that.data.address;
    for (var i = 0; i < list.length; i++) {
      if (list[i].aid == id) {
        var params = {
          aid: id,
          username: list[i].username,
          mobile: list[i].mobile,
          province: list[i].province.name,
          town: list[i].town.name,
          city: list[i].city.name,
          address: list[i].address,
          is_default: 1,
          street: list[i].street.name
        }
        api.POST({
          params: params,
          url: app.globalData.base_url + 'address/modify',
          success: function(res) {
            if (util.isEmpty(res.data.code)) {
              // that.addressList();
              that.setData({
                "controlDome": true
              })
            }
          },
          fail: function(fail) {
            util.showError("网络错误，请检查网络");

          }
        })

      }
    }
  },

  //隐藏地址
  hiddenAddress: function() {
    var that = this;
    that.setData({
      addressCol: true
    })
  },
  //确认收货地址
  confirmAddress: function() {
    this.setData({
      addressCol: true
    })
    this.addressList();
  },
  // 购买方式弹窗控制
  buyPatterns: function() {
    this.setData({
      buyPatterns: false
    })
  },
  // 购买方式选择
  buyType: function(e) {
    var buyType = e.currentTarget.dataset.buytype;
    if (buyType == 2) {
      var addressCol = true
    } else {
      var addressCol = true
    }
    this.setData({
      buy_type: buyType,
      addressCol: addressCol
    })
  },
  // 购买方式确认
  buyTypeConfirm: function() {
    var that = this;
    this.setData({
      buyType: that.data.buy_type,
      buyPatterns: true
    })
  },
  // 发票弹窗控制
  invoiceCol: function() {
    this.setData({
      invoice: false
    })
  },
  // 是否需要发票
  invoiceNeedCol: function(e) {
    this.setData({
      invoiceNeed: e.currentTarget.dataset.invoiceneed
    })
  },
  // 发票类型选择
  invoiceTypeCol: function(e) {
    this.setData({
      invoiceType: e.currentTarget.dataset.invoicetype
    })
  },
  // 发票抬头类型选择
  invoiceTextTypeCol: function(e) {
    this.setData({
      invoiceTextType: e.currentTarget.dataset.invoicetexttype
    })
  },
  // 企业名称输入
  EnameCol: function(e) {
    this.setData({
      Ename: e.detail.value
    })
  },
  // 纳税人识别号
  EnumberCol: function(e) {
    this.setData({
      Enumber: e.detail.value
    })
  },
  // 接收电子发票的邮箱
  EmailCol: function(e) {
    this.setData({
      Email: e.detail.value
    })
  },
  // 企业注册地址
  EaddressCol: function(e) {
    this.setData({
      Eaddress: e.detail.value
    })
  },
  // 企业电话号码
  phoneNumberCol: function(e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  // 企业开户银行
  bankNameCol: function(e) {
    this.setData({
      bankName: e.detail.value
    })
  },
  // 企业银行账号
  bankNumberCol: function(e) {
    this.setData({
      bankNumber: e.detail.value
    })
  },
  // 个人抬头名称
  nameCol: function(e) {
    this.setData({
      name: e.detail.value
    })
  },
  //发票说明控制
  captionCol:function(){
    this.setData({
      captionCol: !this.data.captionCol
    })
  },
  // 确认发票信息
  invoiceConfirm: function() {
    var invoiceType = this.data.invoiceType;
    if (this.data.invoiceNeed == 1) { //是否需要发票
      if (invoiceType == 1) {
        this.setData({
          invoiceTypeCol: true
        })
      } else {
        this.setData({
          invoiceTypeCol: false
        })
      }
      this.invoiceTextTypeDecide();

    } else if (this.data.invoiceNeed == 0) {
      this.setData({
        invoice: true,
        invoiceTypeCol: false
      })
      return true
    }


  },
  // 个人或者企业发票判断
  invoiceTextTypeDecide: function() {
    if (this.data.invoiceTextType == 1) { //个人发票
      this.invoiceTypeDecide();
    } else if (this.data.invoiceTextType = 2) { //企业发票
      if (util.isEmpty(this.data.Ename)) {
        util.showStatus("请输入企业名称");
        return false
      }

      if (util.isEmpty(this.data.Enumber)) {
        util.showStatus("请输入纳税人识别号");
        return false
      }


      if (!util.isEmpty(this.data.phoneNumber)) {
        if (!util.validateMobile(this.data.phoneNumber)) {
          util.showStatus("企业电话号不正确");
          return false
        }
      }

      if (!util.isEmpty(this.data.bankNumber)) {
        if (util.isEmpty(this.data.bankName)) {
          util.showStatus("请输入开户行");
          return false
        }
        if (!util.checkBankNo(this.data.bankNumber)) {
          util.showStatus("银行账号不正确");
          return false
        }
      }

      this.invoiceTypeDecide();
    }
  },

  //发票类型判断
  invoiceTypeDecide: function() {
    if (this.data.invoiceType == 1) { //普通发票
      this.setData({
        invoice: true
      })
      return true
    } else if (this.data.invoiceType = 2) { //电子发票
      var email = this.data.Email;
      email = email.replace(/\s*/g, "");  //去除空格
      // console.log(email);
      // return false
      if (util.validateEmail(email)) {
        this.setData({
          invoice: true
        })
        return true
      } else {
        util.showStatus("邮箱地址错误");
        return false
      }
    }
  },
  // 提交订单
  payOrder: function(e) {
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }

    util.showLoading("数据加载中..");


    var params = new Object()
    var that = this;
    var list = [];
    params.record = [];
    for (var i = 0; i < this.data.items.length; i++) {
      var box = {};
      box.sku_code = this.data.items[i].sku_code
      box.num = this.data.items[i].num
      //summer0306 start
      if (this.data.items[i].inn_id) {
        box.inn_id = this.data.items[i].inn_id
      }
      //summer0306 end
      if (this.data.items[i].shop_id) {
        box.shop_id = this.data.items[i].shop_id
      }
      box.price = this.data.items[i].current_price
      list.push(box);
    }
    console.log('index/order/order');
    console.log(box);

    params.record = JSON.stringify(list);

    if (this.data.invoiceNeed == 1) { //是否需要发票

      if (this.data.invoiceTextType == 1) { //个人发票

        params.invoice = "个人";
        if (this.data.invoiceType == 2) { //电子发票
          params.invoice_email = this.data.Email;
          params.invoice_type = 2
        } else {
          params.invoice_type = 1
        }

      } else if (this.data.invoiceTextType == 2) { //企业发票
        params.invoice = this.data.Ename;
        params.invoice_number = this.data.Enumber;
        if (this.data.invoiceType == 2) { //电子发票
          params.invoice_email = this.data.Email;
          params.invoice_type = 2
        } else {
          params.invoice_type = 1
        }

        if (!util.isEmpty(this.data.Eaddress)) {
          params.invoice_e_r_address = this.data.Eaddress
        }

        if (!util.isEmpty(this.data.phoneNumber)) {
          params.invoice_e_tel = this.data.phoneNumber
        }

        if (!util.isEmpty(this.data.bankNumber)) {
          params.invoice_e_bank_name = this.data.bankName
          params.invoice_e_bank_number = this.data.bankNumber
        }
      }
    }

    params.buy_type = this.data.buy_type
    if (this.data.buy_type == 2) {
      wx.setStorageSync('buy_type', "2");
    } else {
      wx.setStorageSync('buy_type', "1");
    }
    if (this.data.buy_type == 2 || this.data.invoiceTypeCol) {
      var address = this.data.address
      for (var i = 0; i < address.length; i++) {
        if (address[i].is_default == 1) {
          params.aid = address[i].aid
        }
      }

      if (params.aid == undefined || params.aid == '') {
        util.showError("请选择收货地址");
        return false;
      }

    }

    // if (this.data.shop_id) {
    //   params.shop_id = this.data.shop_id
    // }

    if (this.data.share_id) {
      params.share_id = this.data.share_id
    }

    if (this.data.uid) {
      params.share_uid = this.data.uid
    }

    //是否从购物车提交
    if (this.data.by_shopping_cart){
      params.by_shopping_cart = this.data.by_shopping_cart
    }

    // if (app.globalData.shopId){
    //   params.shop_id = app.globalData.shopId
    // }

    if (this.data.orderSubmitCol){
      // util.showError("请勿重复提交订单");
      return false
    }else{
      this.setData({
        orderSubmitCol:true
      })
    }

    console.log('params');
    console.log(params)

    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function(res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          var oid = res.data.data.result.oid;
          var qrcode_image = res.data.data.result.qrcode_image;
          if (qrcode_image) {
            that.setData({
              qrcode_image: qrcode_image
            })
          }
          that.wxPayOrder(oid);
        } else {

          //门店无货，继续购买
          if (res.data.code=='11200'){
            wx.showModal({
              title:'提示',
              content: res.data.message,
              cancelText:'放弃购买',
              confirmText:'继续购买',
              success:function(res){
                if (res.confirm){
                  params.buy_anyway = '1';
                  api.POST({
                    params: params,
                    url: app.globalData.base_url + 'order/submit',
                    success: function (res) {
                      if (util.isEmpty(res.data.code)) {
                        var oid = res.data.data.result.oid;
                        var qrcode_image = res.data.data.result.qrcode_image;
                        if (qrcode_image) {
                          that.setData({
                            qrcode_image: qrcode_image
                          })
                        }
                        that.wxPayOrder(oid);
                      } else {
                        util.showStatus(res.data.message)
                      }
                    },
                    fail: function (fail) {
                      util.showError("网络错误，请检查网络");
                    }
                  })
                }else{
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }else {
            util.showStatus(res.data.message)
          }
        }
      },
      fail: function(fail) {
        util.hiddenLoading();
        util.showError("网络错误，请检查网络");
      }
    })


  },

  // 订单支付
  //支付接口
  wxPayOrder: function(oid) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function(res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function(res) {
              wx.redirectTo({
                url: '/index/pages/paySuccessful/paySuccessful?oid=' + oid
              })
            },
            fail: function(error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderList');
              setTimeout(function() {
                wx.redirectTo({
                   url: '/center/pages/orderDetails/orderDetails?oid=' + oid
                })
              }, 1000)
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function(fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //获取授权信息
  getSetting:function(){
    var  that = this;
    wx.authorize({
      scope: 'scope.invoiceTitle',
      success(res) {
        that.obtainInvoice();
      },
      fail(res) {
        that.setData({
          invoiceAuthorize: '2'
        })
      }
    })
  },

  // 获取微信发票信息
  obtainInvoice: function() {
    var that = this;
    wx.chooseInvoiceTitle({
      success(res) {
        var types = res.type,
          title = res.title,
          telephone = res.telephone,
          taxNumber = res.taxNumber,
          companyAddress = res.companyAddress,
          bankName = res.bankName,
          bankAccount = res.bankAccount

        if (that.data.invoiceTextType == 2) {
          if (types == 0) {
            that.setData({
              Ename: title,
              Enumber: taxNumber,
              Eaddress: companyAddress,
              bankName: bankName,
              bankNumber: bankAccount
            })
          } else {
            util.showError("抬头类型错误");
          }

        }
      },
      fail(){
        that.setData({
          invoiceAuthorize: '2'
        })
      }
    })
  }
})